package com.school.dao.impl;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.school.dao.GradeDao;
import com.school.domain.Grade;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class GradeDaoImpl implements GradeDao {
    private DataSource dataSource = new ComboPooledDataSource();
    private QueryRunner queryRunner = new QueryRunner(dataSource);
    @Override
    public List<Grade> findBySid(long sid) {
        List<Grade> execute = null;
        try {
            execute = queryRunner.query("select * from grade where sid = " + sid, new BeanListHandler<>(Grade.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }

    @Override
    public List<Grade> findByCoid(long coid) {
        List<Grade> execute = null;
        try {
            execute = queryRunner.query("select * from grade where coid = " + coid, new BeanListHandler<Grade>(Grade.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }

    @Override
    public boolean addGrade(Grade grade) {
        int result;
        try {
            result = queryRunner.update("insert into grade values(?, ?, ?, ?)", null, grade.getScore(), grade.getSid(), grade.getCoid());

        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }
}
